/**
 * Nombre del archivo: GUIStackVector.java
 * Fecha de creacion: 13 de julio de 2012
 * Descripcion: interfaz grafica de la calculadora formato Postfix
 */

// Todo lo relacionado con StringTokenizer fue sacado de http://www.leepoint.net/notes-java/data/strings/55stringTokenizer/10stringtokenizer.html
import java.util.StringTokenizer;
import javax.swing.JOptionPane;


/**
 *
 * @author Maria Fernanda Martinez
 */
public class GUIStackVector extends javax.swing.JFrame {
    float resultado;
    Stack<String> vector = new StackVector<String>(); // Vector que guarda los datos de entrada
    Stack<Float> decimal = new StackVector<Float>(); // Vector que se utiliza como pila
    String cadena;
    String operacion;

    /**
     * Creates new form GUIStackVector
     */
    public GUIStackVector() {
        initComponents();
    }

    /**
     * This method is called from within the constructor to initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is always
     * regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {


        jLabel1 = new javax.swing.JLabel();
        jTextField1 = new javax.swing.JTextField();
        jButton1 = new javax.swing.JButton();
        jSeparator1 = new javax.swing.JSeparator();
        jLabel2 = new javax.swing.JLabel();
        jFormattedTextField1 = new javax.swing.JFormattedTextField();
        jButton2 = new javax.swing.JButton();

        setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);

        jLabel1.setText("Ingrese operacion en formato Postfix");

        jTextField1.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jTextField1ActionPerformed(evt);
            }
        });

        jButton1.setText("Aceptar");
        jButton1.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton1ActionPerformed(evt);
            }
        });

        jLabel2.setText("Resultado");

        jFormattedTextField1.setEnabled(false);
        jFormattedTextField1.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jFormattedTextField1ActionPerformed(evt);
            }
        });

        jButton2.setText("Aceptar");
        jButton2.setEnabled(false);
        jButton2.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton2ActionPerformed(evt);
            }
        });

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addGap(27, 27, 27)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(jSeparator1, javax.swing.GroupLayout.PREFERRED_SIZE, 321, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(jLabel1)
                    .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING, false)
                        .addGroup(layout.createSequentialGroup()
                            .addComponent(jLabel2)
                            .addGap(18, 18, 18)
                            .addComponent(jFormattedTextField1, javax.swing.GroupLayout.PREFERRED_SIZE, 184, javax.swing.GroupLayout.PREFERRED_SIZE)
                            .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                            .addComponent(jButton2))
                        .addGroup(javax.swing.GroupLayout.Alignment.LEADING, layout.createSequentialGroup()
                            .addComponent(jTextField1, javax.swing.GroupLayout.PREFERRED_SIZE, 258, javax.swing.GroupLayout.PREFERRED_SIZE)
                            .addGap(27, 27, 27)
                            .addComponent(jButton1))))
                .addContainerGap(32, Short.MAX_VALUE))
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addGap(27, 27, 27)
                .addComponent(jLabel1)
                .addGap(18, 18, 18)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jTextField1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(jButton1))
                .addGap(18, 18, 18)
                .addComponent(jSeparator1, javax.swing.GroupLayout.PREFERRED_SIZE, 10, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addGap(10, 10, 10)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel2)
                    .addComponent(jFormattedTextField1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(jButton2))
                .addContainerGap(40, Short.MAX_VALUE))
        );

        pack();
    }// </editor-fold>//GEN-END:initComponents

    private void jTextField1ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jTextField1ActionPerformed
        // TODO add your handling code here:
    }//GEN-LAST:event_jTextField1ActionPerformed

    private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton1ActionPerformed
        // Limpiar los vectores y cadena que muestra la operacion
        operacion="";
        vector.clear();
        decimal.clear();
        cadena=jTextField1.getText(); // Se obtiene la cadena ingresada por el usuario
        StringTokenizer st = new StringTokenizer(cadena); // Para separar los datos ingresados por el usuario
        /*
         * El ciclo while se utiliza para guardar los datos ingresados por el usuario al vector que
         * simula la pila. 
         */
        while(st.hasMoreTokens())
        {
            vector.push(String.valueOf(st.nextToken())); //Guardar un dato de entrada
            String valor = vector.peek(); //Obtener el dato ingresado
            
            /*
             * La condicion if se utiliza para verificar que el dato ingresado sea numerico; si esto es
             * asi, dicho valor se convierte a un tipo de dato decimal y se guarda en la pila. Luego dicho
             * valor es retirado del vector de entrada. Si el dato no es numerico, se verifica que sea
             * un operador.
             */
            if(vector.isNumeric(valor)){
                decimal.push(Float.parseFloat(vector.peek()));
                operacion+=vector.pop()+" ";                
            }
            else if(vector.isSymbol(valor)){
                operacion+=vector.pop()+" ";// Se retira el simbolo del vector de entrada
                
                // Se verifica que hayan al menos dos operandos
                if(decimal.size()<2){
                    JOptionPane.showMessageDialog(null, "No hay suficientes operandos para \nejecutar la ultima instruccion ingresada");
                    break;
                }
                else{
                    float num2=decimal.pop(); // Se obtiene el segundo operando
                    float num1=decimal.pop(); // Se obtiene el primer operando
                    
                    // Se verifica que no sea división por cero
                    if(num2==0&&valor.equals("/")){
                        JOptionPane.showMessageDialog(null, "División por cero", "Error", JOptionPane.WARNING_MESSAGE);
                        resultado=0; // Se asigna cero al resultado
                    }
                    else
                        resultado=decimal.operate(num1, num2, valor); // Se guarda el resultado de la operacion
                    
                    decimal.push(resultado); // El resultado de la operacion se guarda en la pila
                    jFormattedTextField1.setText(String.valueOf(decimal.peek()));
                    jTextField1.setText(operacion);
                    jButton2.setEnabled(true);
                    jFormattedTextField1.setEnabled(true);
                    jButton1.setEnabled(false);
                    jTextField1.setEnabled(false); 
                    
                }
            }
        }
        
        
    }//GEN-LAST:event_jButton1ActionPerformed

    private void jFormattedTextField1ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jFormattedTextField1ActionPerformed
        // TODO add your handling code here:
    }//GEN-LAST:event_jFormattedTextField1ActionPerformed

    private void jButton2ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton2ActionPerformed
        // TODO add your handling code here:
        jButton2.setEnabled(false);
        jFormattedTextField1.setEnabled(false);
        jFormattedTextField1.setText(null);
        jTextField1.setText(null);
        jButton1.setEnabled(true);
        jTextField1.setEnabled(true);
        
    }//GEN-LAST:event_jButton2ActionPerformed

    /**
     * @param args the command line arguments
     */
    public static void main(String args[]) {
        /*
         * Set the Nimbus look and feel
         */
        //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
        /*
         * If Nimbus (introduced in Java SE 6) is not available, stay with the
         * default look and feel. For details see
         * http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html
         */
        try {
            for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
                if ("Nimbus".equals(info.getName())) {
                    javax.swing.UIManager.setLookAndFeel(info.getClassName());
                    break;
                }
            }
        } catch (ClassNotFoundException ex) {
            java.util.logging.Logger.getLogger(GUIStackVector.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (InstantiationException ex) {
            java.util.logging.Logger.getLogger(GUIStackVector.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (IllegalAccessException ex) {
            java.util.logging.Logger.getLogger(GUIStackVector.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (javax.swing.UnsupportedLookAndFeelException ex) {
            java.util.logging.Logger.getLogger(GUIStackVector.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        }
        //</editor-fold>

        /*
         * Create and display the form
         */
        java.awt.EventQueue.invokeLater(new Runnable() {

            @Override
            public void run() {
                new GUIStackVector().setVisible(true);
            }
        });
    }
    // Variables declaration - do not modify//GEN-BEGIN:variables

    private javax.swing.JButton jButton1;
    private javax.swing.JButton jButton2;
    private javax.swing.JFormattedTextField jFormattedTextField1;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JLabel jLabel2;
    private javax.swing.JSeparator jSeparator1;
    private javax.swing.JTextField jTextField1;
    // End of variables declaration//GEN-END:variables
}
